/*
 * SessionMonitorApp.java
 */

package pl.edu.agh.ssm.monitor;

//import java.util.HashMap;
import java.util.List;
//import java.util.Properties;
//import java.util.Set;
import jpcap.NetworkInterface;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.Task;
//import pl.edu.agh.ssm.monitor.data.Session;
import pl.edu.agh.ssm.monitor.data.SessionData;
import pl.edu.agh.ssm.monitor.listeners.ListenerConfig;
//import pl.edu.agh.ssm.monitor.listeners.PacketListener;
//import pl.edu.agh.ssm.monitor.listeners.SessionMonitorListener;
import pl.edu.agh.ssm.monitor.net.PacketReceiver;
import pl.edu.agh.ssm.monitor.plotter.DataPlotter;
//import pl.edu.agh.ssm.monitor.plotter.SessionPlotter;

/**
 * The main class of the application.
 */
public class SessionMonitorApp extends SingleFrameApplication {

    /**
     * Initialization of SessionMonitor.
     * Command line parameters are passed to this method and can be interpreted here.
     * @param args command line arguments
     */
    @Override
    protected void initialize(String[] args) {
//        try {
//            String propertiesFile = getContext().getResourceMap().getString("SessionMonitor.defaultProperties");
//            if (args.length > 1 && args[0].equals("-p")) {
//                propertiesFile = args[1];
//            }
//            this.properties = new Properties();
//            this.properties.load(new FileInputStream(propertiesFile));
//        } catch (IOException ex) {
//            Logger.getLogger(SessionMonitorApp.class.getName()).log(Level.SEVERE, null, ex);
//        } 
                view = new SessionMonitorView(this);
                manager = new DefaultSessionMonitorManager();
    }
    
    /**
     * At startup create and show the main frame of the application.
     */
    @Override
    protected void startup() {

        show(view);
    }
    
    /**
     * Invoked after startup.
     * @see SingleFrameApplication#ready()
     */
    @Override
    protected void ready() {
        /**
         * @todo later remove all this stuff and make it dynamically loaded or at least created by some kind of ListenerFactory
         */
        //SessionMonitorListener testListener = new SDPSessionMonitorListener();
        //testListener.addPlotter(new SDPDataPlotter());
        //this.listeners.put("SDP", testListener);
    }

    /**
     * This method is to initialize the specified window by injecting resources.
     * Windows shown in our application come fully initialized from the GUI
     * builder, so this additional configuration is not needed.
     */
    @Override protected void configureWindow(java.awt.Window root) {
    }
    
    /**
     * 
     */
     public SessionMonitorView getView() {
         return view;
     }
     
     public SessionMonitorManager getManager() {
         return manager;
     }
     
//     public Set<String> getListenerTypes() {
//         return listeners.keySet();
//     }
//     
//     public SessionMonitorListener getListener(String type) {
//         return listeners.get(type);
//     }
     
    /**
     * A convenient static getter for the application instance.
     * @return the instance of SessionMonitorApp
     */
    public static SessionMonitorApp getApplication() {
        return Application.getInstance(SessionMonitorApp.class);
    }

    /**
     * Main method launching the application.
     */
    public static void main(String[] args) {
        launch(SessionMonitorApp.class, args);
    }
    
    public static class StartAppTask extends Task<Void, Void> {

        public StartAppTask(NetworkInterface networkIface, boolean promiscuous, List<ListenerConfig> configs, Application app) {
            super(app);
            this.networkIface = networkIface;
            this.promiscuous = promiscuous;
            this.configs = configs;
        }
        
        public StartAppTask(NetworkInterface networkIface, boolean promiscuous, List<ListenerConfig> configs) {
            this(networkIface, promiscuous, configs, SessionMonitorApp.getApplication());
        }
        
        @Override
        protected Void doInBackground() throws Exception {
            this.setMessage("Starting listeners...");
            float progressUnit = 1.0f / (float)((configs.size() + 1) * 2);
            SessionMonitorManager manager = SessionMonitorApp.getApplication().getManager();
            manager.cleanup();
            PacketReceiver receiver = new PacketReceiver(networkIface, promiscuous);
            setProgress(progressUnit);
            int counter = 1;
            for (ListenerConfig config : configs) {
                manager.addListener(receiver, config);
                setProgress((float)++counter * progressUnit);
                System.out.println("Added listener " + config.getType());
            }
            //end
            SessionStateAgent agent = new SessionStateAgent();
            manager.setup(receiver, agent);
            
            receiver.start();
            agent.start();
            return null;
        }
        
        @Override
        protected void succeeded(Void ignored) {
            setMessage("Preparing view...");
            SessionMonitorApp.getApplication().getView().removeAllTabs();
            List<DataPlotter<? extends SessionData> > plotters = SessionMonitorApp.getApplication().getManager().getCreatedPlotters();
            float startProgress = ((float) getProgress()) / 100f;
            System.out.println("sp " + startProgress);
            float progressUnit = 1.0f / (float)(plotters.size() * 2);
            int counter = 1;
            for (DataPlotter<? extends SessionData> p : plotters) {
                p.prepareView(SessionMonitorApp.getApplication().getView());
                setProgress(startProgress + ((float)counter++ * progressUnit));
            }
            System.out.println("Listeners started");
        }
        
        private NetworkInterface networkIface;
        private boolean promiscuous;
        private List<ListenerConfig> configs;
    }
    
    public static class TestTask extends Task<Void, Void> {
        
        public TestTask(Application app) {
            super(app);
        }
        
        @Override
        protected Void doInBackground() throws Exception {
            setProgress(0.7f);
            Thread.sleep(20000);
            return null;
        }
        
    }
    
    private SessionMonitorView view = null;
    private SessionMonitorManager manager;// = new DefaultSessionMonitorManager();
//    private Properties properties = null;
//    private HashMap<String, SessionMonitorListener> listeners = new HashMap<String, SessionMonitorListener>();
}
